#!/usr/bin/python
# -*- coding: utf-8 -*-

__author__ = "Pawel Misiak <misiak.pawel@gmail.com>"
__copyright__ = "Copyright (C) 2014 Pawel Misiak"
__license__ = "LGPL 3.0"

from .fpdf import FPDF

class NoPdfDocumen(Exception):
	def __init__(self, message="No PDF document specyfied"):
		Exception.__init__(self, message)

class TablePdf:
	"Table generation class for fpdy"

	__pdfDoc = None

	def __init__(self, pdfDoc = None):
		if pdfDoc==None:
			self.__pdfDoc = self
		else:
			self.__pdfDoc = pdfDoc

	def defineTable(self, colWidths, rowCount, header=True):
		"Define table with column width and row count. Header is aviable by default, but maybe turned off"
		localTab = TablePdf(self.__pdfDoc)
		localTab.colWidths = colWidths
		localTab.colCount = len(colWidths)
		localTab.rowCount = rowCount
		localTab.data = rowCount*[None]
		localTab.data = []
		localTab.header = header
		for i in range(0, rowCount):
			localTab.data.append( localTab.colCount * [""] )
		return localTab

	def __setitem__(self, args, val):
		row = args[0]
		col = args[1]
		self.data[row][col] = str(val)

	def __getitem__(self, args):
		row = args[0]
		col = args[1]
		return self.data[row][col]

	def dumpTable(self):
		"Dump table, for debugging"
		for row in range(0, self.rowCount):
			for col in range(0, self.colCount):
				print self.data[row][col],
			print

	def __getMaxLines(self):
		pdfDoc = self.__pdfDoc
		rowsLines=[]
		for row in range(0, self.rowCount):
			maxLines = 1
			linesInString=[]
			for col in range(0, self.colCount):
				ret = pdfDoc.multi_cell(self.colWidths[col], 5, self.data[row][col], 1, "L", row==0, True)
				tmpLines = len(ret)
				linesInString.append(tmpLines)
				if tmpLines > maxLines:
					maxLines=tmpLines
			rowsLines.append([maxLines,linesInString])
		return rowsLines

	def __updateDataLines(self):
		pdfDoc = self.__pdfDoc
		rowsLines = self.__getMaxLines()
		for row in range(0, self.rowCount):
			for col in range(0, self.colCount):
				toAdd = rowsLines[row][0] - rowsLines[row][1][col]
				if toAdd:
					self.data[row][col] += toAdd*"\n" + "\n"

	def drawTable(self, posX, posY):
		"Draw table on specified position X,Y"
		if self.__pdfDoc == None:
			raise NoPdfDocumen

		pdfDoc = self.__pdfDoc
		pdfDoc.set_xy(posX, posY)
		tabLength = self.colWidths
		fontSize = pdfDoc.font_size_pt 
		font = pdfDoc.font_family

		self.__updateDataLines()
		if self.header:
			pdfDoc.set_font(font, 'B', fontSize-2)
		for row in range(0, self.rowCount):
			currentX = posX
			currentY = pdfDoc.get_y()
			for col in range(0, self.colCount):
				pdfDoc.set_xy(currentX, currentY)
				if row==0 and self.header:
					pdfDoc.multi_cell(tabLength[col], 3, self.data[row][col], 1, "C", 1)
				else:
					pdfDoc.multi_cell(tabLength[col], 5, self.data[row][col], 1, "L", 0)
				currentX += tabLength[col]
			if row==0:
				pdfDoc.set_font(font, '', fontSize)


